from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync
import time


class ChatView(WebsocketConsumer):
    def websocket_connect(self, message):
        self.accept()
        group = self.scope['url_route']['kwargs'].get("group")
        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

    def websocket_receive(self, message):
        group = self.scope['url_route']['kwargs'].get("group")
        async_to_sync(self.channel_layer.group_send)(group, {"type": "chat", 'message': message})

    def chat(self, event):
        text = event['message']['text']
        self.send(text)

    def websocket_disconnect(self, message):
        group = self.scope['url_route']['kwargs'].get("group")
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        print('客户端断开连接了')
        raise StopConsumer()



    # def websocket_connect(self, message):
    #     # 客户端与服务端进行握手时，会触发这个方法
    #     # 服务端允许客户端进行连接，就是握手成功
    #     self.accept()
    #
    # def websocket_receive(self, message):
    #     # 接收到客户端发送的数据
    #     recv = message.get('text')
    #     print('接收到的数据，', recv)
    #     if recv == 'close':
    #         # 服务的主动断开连接
    #         print('服务器断开连接')
    #         self.close()
    #     else:
    #         # 客户端向服务端发送数据
    #         # self.send(f'我收到了，{time.strftime("%Y-%m-%d %H:%M:%S")}')
    #         self.send(recv)
    #
    # def websocket_disconnect(self, message):
    #     # 客户端端口连接时，会触发该方法，断开连接
    #     print('客户端断开连接')
    #     raise StopConsumer()